package cn.kone.listener;

import cn.hutool.core.util.RandomUtil;
import cn.kone.pojo.domain.PayOrder;
import cn.kone.pojo.dto.OrderPayDTO;
import cn.kone.service.IPayOrderService;
import cn.kone.util.GtUtil;
import cn.kone.util.WeChatUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@RocketMQMessageListener(consumerGroup = "service-consumer", topic = "orderPay_topic", selectorExpression = "orderPay_tags")
public class OrderListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;


    @Override
    public void onMessage(MessageExt message) {
        String json = new String(message.getBody(), StandardCharsets.UTF_8);// 将消息体转换为字符串
        OrderPayDTO orderPayDTO = JSON.parseObject(json, OrderPayDTO.class);// 将 JSON 字符串转换为 OrderPayDTO 对象

        //先做健壮性判断,先查询,然后再插入
        PayOrder one = payOrderService.getOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getOrderNo, orderPayDTO.getOrderNo()));
        if (one==null) {
            PayOrder payOrder = new PayOrder();// 创建一个 PayOrder 对象，并设置属性值
            payOrder.setId(Long.valueOf(orderPayDTO.getOrderNo()));
            payOrder.setCreateTime(new Date());
            payOrder.setAmount(orderPayDTO.getOrderAmount());
            payOrder.setPayType(1);
            payOrder.setOrderNo(orderPayDTO.getOrderNo());
            payOrder.setPayUserId(orderPayDTO.getCustomerId());
            payOrder.setSubject(orderPayDTO.getSubject());
            payOrder.setPayStatus(0);
            // 生成支付订单号，使用当前时间加随机字符串的方式
            String format = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
            payOrder.setPayOrderNo(RandomUtil.randomString(6) + format);

            // 调用支付订单服务的保存方法，将支付订单信息保存到数据库中
            payOrderService.save(payOrder);
        }


        //发送账单成功以后1'
        Map<String, Object> map = new HashMap<>();// 创建一个新的 HashMap 对象，用于存储推送消息的相关信息
        map.put("orderNo", orderPayDTO.getOrderNo());// 将订单号放入 map 中，key 为 "orderNo"，value 为 orderPayDTO 中的订单号
        map.put("msgType", 0);// 将消息类型放入 map 中，这里消息类型为 0，key 为 "msgType"，value 为 0

        String jsonString = JSON.toJSONString(map); // 将 map 对象转换为 JSON 字符串，以便于推送

        GtUtil.pushSingleMessageByAlias(orderPayDTO.getCustomerId() + "", jsonString);// 调用 GtUtil 工具类的 pushSingleMessageByAlias 方法，向指定的客户发送推送消息

        //通过Java代码进行发送微信订阅消息进行推送
        WeChatUtil.sendPs();
    }
}
